package bma.common.netty.thrift.dual;

import org.apache.thrift.TBase;
import org.apache.thrift.TFieldIdEnum;
import org.apache.thrift.protocol.TMessageType;
import org.apache.thrift.protocol.TProtocol;

import bma.common.langutil.ai.AIUtil;
import bma.common.langutil.ai.stack.AIStack;
import bma.common.langutil.ai.stack.AIStackStep;

public class NTSBaseServiceClient {

	protected String moduleName;
	protected NTSClient client;
	protected int timeout;

	public NTSBaseServiceClient(NTSClient cl, String module) {
		this(cl, module, 5000);

	}

	public NTSBaseServiceClient(NTSClient client, String moduleName, int timeout) {
		super();
		this.moduleName = moduleName;
		this.client = client;
		this.timeout = timeout;
	}

	public String getModuleName() {
		return moduleName;
	}

	public void setModuleName(String moduleName) {
		this.moduleName = moduleName;
	}

	public int getTimeout() {
		return timeout;
	}

	public void setTimeout(int timeout) {
		this.timeout = timeout;
	}

	public <TYPE> boolean invoke(AIStack<TYPE> stack, final TBase result,
			final String name, final TBase avgs) {
		try {
			String callName;
			if (this.moduleName != null) {
				callName = this.moduleName + "." + name;
			} else {
				callName = name;
			}
			AIStackStep<NTSResponse, TYPE> step = new AIStackStep<NTSResponse, TYPE>(
					stack) {
				@Override
				protected boolean next(NTSResponse response) {
					try {
						TProtocol in = response.getInputProtocol();
						result.read(in);
						in.readMessageEnd();
					} catch (Exception err) {
						return failure(err);
					}
					TFieldIdEnum field = result.fieldForId(0);
					if (field != null) {
						return successForward((TYPE) result
								.getFieldValue(field));
					} else {
						return successForward(null);
					}
				}
			};
			client.write(step, callName, result == null ? TMessageType.ONEWAY
					: TMessageType.CALL, avgs, timeout);
			return false;
		} catch (Exception e) {
			return AIUtil.safeFailure(stack, e);
		}
	}

}
